package es.qb.deportivos.il.dal.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import es.qb.deportivos.exception.GeneralDAOException;
import es.qb.deportivos.il.dal.interfaces.TesoreriaDAO;
import es.qb.deportivos.il.domain.Tesoreria;
import es.qb.deportivos.util.Utilities;

public class TesoreriaDAOImpl extends GeneralDAOImpl<Tesoreria> implements TesoreriaDAO {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Double calculaTotal() throws GeneralDAOException {

		Double dTotal = 0D;

		try {

			CriteriaBuilder criteriaBuilder = getJpaTemplate().getEntityManager().getCriteriaBuilder();
			CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();

			Root<Tesoreria> from = criteriaQuery.from(Tesoreria.class);

			List<Predicate> lstPredicateAux2 = new ArrayList<Predicate>();
			Predicate predicateAux3 = criteriaBuilder.equal(from.get("borradoLogico"), 0);
			lstPredicateAux2.add(predicateAux3);

			Predicate predicateAux4 = criteriaBuilder.notEqual(from.get("concepto"), "Pendiente de pago");
			lstPredicateAux2.add(predicateAux4);

			criteriaQuery.where(criteriaBuilder.and(Utilities.crearPredicateVariable(lstPredicateAux2)));

			Expression minExpression = criteriaBuilder.sum((Expression) from.get("importe"));
			CriteriaQuery<Object> select = criteriaQuery.select(minExpression);

			TypedQuery<Object> typedQuery = getJpaTemplate().getEntityManager().createQuery(select);
			dTotal = (Double) typedQuery.getSingleResult();

			return dTotal;
		} catch (PersistenceException e) {
			throw new GeneralDAOException("IL-DAL-BUSCARPUNTOS", "Se ha producido un error al buscar los puntos." + e);
		}
	}
}
